package com.wyh.yuhcloud.util;

import org.springframework.stereotype.Component;

import java.util.Random;

@Component
public class DiyIDUtils {
    //业务名称
    private String projectName;
    //时间戳中固定长度字符串 默认4位
    private String timestampSub;
    //默认时间字段长度
    private long defaultNum = 4L;
    //初始序号 1开始
    private long sequence = 1L;
    //记录产生时间毫秒数，判断是否是同1毫秒
    private long lastTimestamp = -1L;


    public DiyIDUtils() {
    }

    public DiyIDUtils(String projectName, long defaultNum, long sequence) {
        this.projectName = projectName;
        this.defaultNum = defaultNum;
        this.sequence = sequence;
    }

    public DiyIDUtils(String projectName, long sequence) {
        this.projectName = projectName;
        this.sequence = sequence;
    }


    public synchronized String nextId(){
        long timestamp = System.currentTimeMillis();
        StringBuilder sb = new StringBuilder();
        sb.append(this.projectName);
        long time = timestamp % 1000;
        sb.append(time);
        if (timestamp == lastTimestamp){
            this.sequence += 1;
            sb.append(this.sequence);
        }else{
            this.sequence = 1;
            sb.append(this.sequence);
        }
        //sb.append(hashCode());

        sb.append(time+new Random().nextInt(100));

        this.lastTimestamp = timestamp;
        return sb.toString();
    }

    public synchronized String nextId(String phone){
        long timestamp = System.currentTimeMillis();
        StringBuilder sb = new StringBuilder();
        sb.append(this.projectName);
        long time = timestamp % 1000;
        sb.append(time);
        if (timestamp == lastTimestamp){
            this.sequence += 1;
            sb.append(this.sequence);
        }else{
            this.sequence = 1;
            sb.append(this.sequence);
        }
        //sb.append(hashCode());
        if (phone!=null && phone.length()==11){
            sb.append(Integer.parseInt(phone.substring(7,10))+new Random().nextInt(100));
        }else{
            sb.append(time+new Random().nextInt(100));
        }
        this.lastTimestamp = timestamp;
        return sb.toString();
    }


}
